<template>
  <div data-flex="cross:center">
    <el-input @keyup.enter.native="onEnter" v-model="mValue" v-bind="attrs" :size="size" :clearable="clearable"></el-input>
    <span v-if="img" v-html="img" class="m-l-10 img" @click="getImg" data-flex-box="0"></span>
  </div>
</template>

<script>
export default {
  name: 'OsCaptcha',
  props: {
    size: String,
    clearable: Boolean,
    attrs: Object,
    value: String
  },
  data () {
    return {
      img: ' ',
      mValue: this.value
    }
  },
  watch: {
    mValue (val) {
      this.$emit('input', val)
    }
  },
  created () {
    this.getImg()
    console.log(this)
  },
  methods: {
    async getImg () {
      const { data } = await this.$store.dispatch(this.$config?.actions?.captcha || 'captcha')
      if (data) {
        if (!data.img) {
          const src = 'data:image/jpeg;base64,' + btoa(
            new Uint8Array(data).reduce((data, byte) => data + String.fromCharCode(byte), '')
          )
          this.img = `<img src="${src}" width="108" height="36"/>`
        } else {
          this.img = data.img
        }
        this.$emit('change', { code: data.captchaCode, refresh: this.getImg })
      }
    },
    onEnter () {
      this.$emit('enter')
    }
  }
}
</script>

<style lang="scss" scoped>
  .img{
    cursor: pointer;
    width: 108px;
    height: 36px;
    overflow: hidden;
  }
</style>
